#include "udpServer.hpp"
#include <memory>
#include <unordered_map>
#include <fstream>
#include<signal.h>


using namespace Server;
void myperr(const char *message)
{
    printf("%s,使用错误，需要加上端口号\n", message);
}


const string dictTxt = "./dict.txt";
unordered_map<string, string> dict;
static bool cutString(const string &target, string *s1, string *s2, const string &sep)
{
    auto pos = target.find(sep);
    if (pos == string::npos)
        return false;
    *s1 = target.substr(0, pos);
    *s2 = target.substr(pos + sep.size());
    return true;
}

// #define FILE_NAME "dict.txt"

static void initDict()
{
    ifstream in(dictTxt, ios::binary);
    if (!in.is_open())
    {
        perror("open");
        exit(1);
    }

    string line;
    string key, value;
    while (getline(in, line))
    {
        cout<<line<<endl;
        if (cutString(line, &key, &value, ":"))
        {
            dict.insert(make_pair(key, value));
        }
    }
    in.close();

    cout<<"load dict success"<<endl;
}

static void debugPrint()
{
    for (auto& e : dict)
    {
        cout << e.first << "#" << e.second << endl;
    }
}

// 业务1：实现一个字典，客户端发送单词给服务器，服务器翻译后发回给客户端
void handlerMassage(int sock,string clientip, uint16_t clientport, string message)
{
    string response_message;
    auto iter = dict.find(message);
    if(iter == dict.end()) response_message = "unknow";
    else response_message = iter->second;

    //开始返回
    sockaddr_in client;
    bzero(&client,sizeof(client));
    client.sin_family = AF_INET;
    client.sin_port = htons(clientport);
    client.sin_addr.s_addr = inet_addr(clientip.c_str());

    sendto(sock,response_message.c_str(),response_message.size(),0,(sockaddr*)&client,sizeof(client));



}
void reload(int signo){
    (void)signo;
    initDict();
}
int main(int argc, char *argv[])
{
   // signal(2,reload);
    if (argc != 2)
    {
        myperr(argv[0]);
        exit(1);
    }

    uint16_t port = atoi(argv[1]);

    unique_ptr<udpServer> ret(new udpServer(handlerMassage, port));
    //initDict();
    //debugPrint();
    ret->initServer();
    ret->start();


    return 0;
}